Page({
  data: {
    stockCode:'',
    stockName: '',
    openPrice: '',
    yesterdayClose: '',
    currentPrice: '',
    highestPrice: '',
    lowestPrice: '',
    turnoverRate: '',
    volume: '',
    amount: '',
    priceChange: '',
    buyOrders: [],
    sellOrders: [],
    choose:false,
  },
  onLoad: function(options) {
    const stockCode = options.stockCode;
    let formattedStockCode = this.formatStockCode(stockCode);
    this.setData({
      stockCode: formattedStockCode
    });
    const openid = wx.getStorageSync('openid');
    wx.cloud.callFunction({
      name: 'checkStock',
      data: { 
        stockCode:this.data.stockCode,
        openid
       },
      success: res => {
        if(res)
        console.log(res)
        this.setData({
          choose:res.result.isInSelectedStock
        })
        },
        fail: err => {
          console.error('调用云函数失败', err);
        }
      })
    this.fetchStockData();
    this.switchChart({ currentTarget: { dataset: { chart: 'min' } } });
  },
  fetchStockData() {
    const stockCode = this.data.stockCode;
    wx.request({
      url: `https://hq.sinajs.cn/list=${stockCode}`,
      success: (res) => {
        const dataStr = res.data.match(/"([^"]*)"/)[1];
        const dataArr = dataStr.split(',');

        const stockName = dataArr[0];
        const openPrice = parseFloat(dataArr[1]).toFixed(2);
        const yesterdayClose = parseFloat(dataArr[2]).toFixed(2);
        const currentPrice = parseFloat(dataArr[3]).toFixed(2);
        const highestPrice = parseFloat(dataArr[4]).toFixed(2);
        const lowestPrice = parseFloat(dataArr[5]).toFixed(2);
        const volume = (parseInt(dataArr[8]) / 1000000).toFixed(1) + '万';
        const amount = (parseInt(dataArr[9]) / 100000000).toFixed(1) + '亿元';
        const priceChange = (((currentPrice-openPrice) / openPrice)* 100).toFixed(2)  +` `+ (((currentPrice-yesterdayClose) / yesterdayClose) * 100).toFixed(2) + '%';
        const turnoverRate = ((volume / (parseInt(dataArr[8]) / 10000)) * 100).toFixed(2) + '%';

        let buyOrders = [];
        for (let i = 10; i <= 18; i += 2) {
          buyOrders.push({
            price: parseFloat(dataArr[i + 1]).toFixed(2),
            volume: (parseInt(dataArr[i]) / 1000000).toFixed(2) + '万'
          });
        }

        let sellOrders = [];
        for (let i = 20; i <= 28; i += 2) {
          sellOrders.push({
            price: parseFloat(dataArr[i + 1]).toFixed(2),
            volume: (parseInt(dataArr[i]) / 1000000).toFixed(2) + '万'
          });
        }

        this.setData({
          stockName,
          openPrice,
          yesterdayClose,
          currentPrice,
          highestPrice,
          lowestPrice,
          turnoverRate,
          volume,
          amount,
          priceChange,
          buyOrders,
          sellOrders
        });

        wx.setNavigationBarTitle({
          title: `${stockName} (${stockCode})`
        });
      }
    });
  },
  switchChart(e) {
    const chartType = e.currentTarget.dataset.chart;
    let chartSrc = '';
    const stockCode = this.data.stockCode;
    switch (chartType) {
      case 'min':
        chartSrc = `http://image.sinajs.cn/newchart/min/n/${stockCode}.gif`;
        break;
      case 'daily':
        chartSrc = `http://image.sinajs.cn/newchart/daily/n/${stockCode}.gif`;
        break;
      case 'weekly':
        chartSrc = `http://image.sinajs.cn/newchart/weekly/n/${stockCode}.gif`;
        break;
      case 'monthly':
        chartSrc = `http://image.sinajs.cn/newchart/monthly/n/${stockCode}.gif`;
        break;
      default:
        chartSrc = `http://image.sinajs.cn/newchart/min/n/${stockCode}.gif`;
    }

    this.setData({ chartSrc });
  },
  previewImage() {
    wx.previewImage({
      urls: [this.data.chartSrc]
    });
  },
  addStock() {
    const stockCode = this.data.stockCode;
    const openid = wx.getStorageSync('openid');
    if (!openid) {
      // 如果 openid 为空，跳转到登录界面
      wx.navigateTo({
        url: '/pages/login/login' // 请根据实际登录页面的路径进行调整
      });
      return; // 终止后续操作
    }
    wx.cloud.callFunction({
      name: 'addStock',
      data: { 
        stockCode,
        openid
       },
      success: res => {
        wx.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 2000
        });
        this.setData({
          choose : !this.data.choose
        });
        },
        fail: err => {
          wx.showToast({
            title: '删除失败',
            icon: 'error',
            duration: 2000
          });
          console.error('调用云函数失败', err);
        }
      })
  },
  deleteStock() {
    const stockCode = this.data.stockCode;
    const openid = wx.getStorageSync('openid');
    if (!openid) {
      // 如果 openid 为空，跳转到登录界面
      wx.navigateTo({
        url: '/pages/login/login' 
      });
      return; // 终止后续操作
    }
    wx.cloud.callFunction({
      name: 'deleteStock',
      data: { 
        stockCode,
        openid
       },
      success: res => {
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000
        });
        this.setData({
          choose : !this.data.choose
        });
        },
        fail: err => {
          wx.showToast({
            title: '删除失败',
            icon: 'error',
            duration: 2000
          });
          console.error('调用云函数失败', err);
        }
      })
  },
  onShareAppMessage: function (res) {
    return {
      title: '同花顺模拟炒股',
      path: '/pages/index/index',
      success: function (res) {
        console.log('分享成功', res);
      },
      fail: function (res) {
        console.log('分享失败', res);
      }
    };
  },
  // 定义格式转换函数
  formatStockCode: function(stockCode) {
    // 拆分代码和市场部分
    let [code, market] = stockCode.split('.');
    if(market){
      // 转换市场部分为小写
    market = market.toLowerCase();
    // 拼接成新的格式
    return market + code;
    }
    else{
      return code;
    }
  },

});
